package cn.droidlover.xdroidmvp.mvp;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.githang.statusbar.StatusBarCompat;
import com.trello.rxlifecycle2.components.support.RxFragmentActivity;

import java.util.Calendar;

import butterknife.Unbinder;
import cn.droidlover.xdroidmvp.R;
import cn.droidlover.xdroidmvp.imageloader.ILoader;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.KnifeKit;
import cn.droidlover.xdroidmvp.kit.NLog;
import cn.droidlover.xdroidmvp.view.SimpleLoadDialog;

/**
 * Created by wanglei on 2016/12/29.
 */

public abstract class XActivity<P extends IPresent> extends RxFragmentActivity implements IView<P> {

    private VDelegate vDelegate;
    private P p;
    protected Activity context;
    private Unbinder unbinder;
    public String TAG;
    protected View nodataView;
    public View mainView;
    //    public LinearLayout errorLayout;
    ImageView error_Iv;
    TextView errorTitleTv;
    TextView errorDescTv;
    TextView refreshTv;

    public ImageView leftIv;
    public TextView titleTv;
    public TextView rightTv;
    public View titleLayout;
    protected SimpleLoadDialog simpleLoadDialog;
    public ILoader.Options options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TAG = this.getClass().getSimpleName();
        NLog.d("Activity", "启动的Activity=" + TAG);
        context = this;
        setRequestedOrientation();
        if (getContentViewId() > 0) {
            setContentView(mergeMainView());
            setTotalBar();
            bindUI(null);
            bindEvent();
        }
        options = new ILoader.Options(R.mipmap.refresh_head_arrow, R.mipmap.refresh_head_arrow);

        getIntentData();
        initView();
        initData(savedInstanceState);
//        ViewUtils.setImmersionStateMode(this);
    }

    public void setRequestedOrientation() {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    @Override
    public void initView() {
        simpleLoadDialog = new SimpleLoadDialog(this, true);
        titleLayout = findViewById(R.id.titleLayout);
        leftIv = findViewById(R.id.leftIv);
        titleTv = findViewById(R.id.titleTv);
        rightTv = findViewById(R.id.rightTv);

        error_Iv = findViewById(R.id.errorIv);
        errorTitleTv = findViewById(R.id.errorTitleTv);
        errorDescTv = findViewById(R.id.errorDescTv);
        refreshTv = findViewById(R.id.refreshTv);
        if (null != refreshTv) {
            refreshTv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    toRefresh();
                }
            });
        }

    }


    @Override
    public void initData(Bundle savedInstanceState) {
        if (isNotWorkConnect()) {
            showNoNetPage();
        }
        getDataFromServer();
    }

    public boolean isNotWorkConnect() {
        return false;
//        if (Kits.NetWork.getNetworkTypeName(this) == Kits.NetWork.NETWORK_TYPE_DISCONNECT) {
//            return true;
//        } else {
//            return false;
//        }
    }


    public abstract void getDataFromServer();

    public void onLeftBtnClick(View view) {
        onBackPressed();
    }

    public void showLoadDialog() {
        if (null != simpleLoadDialog) {
            simpleLoadDialog.show();
        }else{
            simpleLoadDialog = new SimpleLoadDialog(this, true);
            simpleLoadDialog.show();
        }
    }

    public void showLoadDialog(String msg) {
        if (null != simpleLoadDialog) {
            simpleLoadDialog.show(msg);
        }
    }

    @Override
    public void disLoadDialog() {
        if (null != simpleLoadDialog) {
            simpleLoadDialog.dismiss();
        }
    }

    Toast mToast;

    @Override
    public void showToast(String content) {
        disLoadDialog();
        if (mToast == null) {
            mToast = Toast.makeText(this, content, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(content);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    @Override
    public void twinkCompleted() {

    }

    public void hideTitle() {
        titleLayout.setVisibility(View.GONE);
    }

    public void setTotalBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            StatusBarCompat.setStatusBarColor(this, Color.rgb(00, 00, 00), true);
        } else {
            StatusBarCompat.setStatusBarColor(this, Color.rgb(00, 00, 00), true);
        }
    }

    @Override
    public void bindUI(View rootView) {
        unbinder = KnifeKit.bind(this);
    }

    protected boolean isVisible(View view) {
        return view.getVisibility() == View.VISIBLE;
    }

    protected void gone(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.GONE);
                }
            }
        }
    }

    protected void visible(final View... views) {
        if (views != null && views.length > 0) {
            for (View view : views) {
                if (view != null) {
                    view.setVisibility(View.VISIBLE);
                }
            }
        }

    }

    protected VDelegate getvDelegate() {
        if (vDelegate == null) {
            vDelegate = VDelegateBase.create(context);
        }
        return vDelegate;
    }

    protected P getP() {
        if (p == null) {
            p = newP();
            if (p != null) {
                p.attachV(this);
            }
        }
        return p;
    }

    @Override
    protected void onStart() {
        super.onStart();
//        if (useEventBus()) {
//            BusProvider.getBus().register(this);
//        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        getvDelegate().resume();

    }


    @Override
    protected void onPause() {
        super.onPause();
        getvDelegate().pause();
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (useEventBus()) {
//            BusProvider.getBus().unregister(this);
//        }
    }

    @Override
    public boolean useEventBus() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (getP() != null) {
            getP().detachV();
        }
        getvDelegate().destory();
        p = null;
        vDelegate = null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (getOptionsMenuId() > 0) {
            getMenuInflater().inflate(getOptionsMenuId(), menu);
        }
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public int getOptionsMenuId() {
        return 0;
    }

    @Override
    public void bindEvent() {

    }

    public void coloseInputWindow() {
        InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View view = this.getCurrentFocus();
        if (null != view) {
            mInputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private View mergeMainView() {

        View viewGroup = getPageView();
        FrameLayout baseMainLayout = viewGroup.findViewById(R.id.baseMainLayout);
        LinearLayout errorLayout = viewGroup.findViewById(R.id.errorLayout);
        int contentId = getContentViewId();
        mainView = LayoutInflater.from(this).inflate(contentId, null, false);
        baseMainLayout.addView(mainView);

        View errorView = LayoutInflater.from(this).inflate(R.layout.nodata_layout, null, false);
        errorLayout.addView(errorView);
        nodataView = errorLayout;
        return viewGroup;
    }

    protected View getPageView() {
        int titleViewId = getTitleLayoutResId();
        View viewGroup;
        if (titleViewId == 0) {
            viewGroup = LayoutInflater.from(this).inflate(R.layout.basepage, null, false);
        } else {
            View titleView = LayoutInflater.from(this).inflate(titleViewId, null, false);
            viewGroup = LayoutInflater.from(this).inflate(R.layout.basepage2, null, false);
            LinearLayout titleContentLayout = viewGroup.findViewById(R.id.titleContentLayout);
            titleContentLayout.addView(titleView);
        }
        return viewGroup;
    }

    public int getTitleLayoutResId() {
        return R.layout.title_layout;

    }

    @Override
    public boolean showNoDataPage() {
        mainView.setVisibility(View.INVISIBLE);
        nodataView.setVisibility(View.VISIBLE);
        setErrorInfo("暂无数据信息哦","请您稍后再来查看吧~~",R.drawable.nodata);
        refreshTv.setText("刷新");
        return true;
    }

    @Override
    public boolean showNoNetPage() {
        mainView.setVisibility(View.INVISIBLE);
        nodataView.setVisibility(View.VISIBLE);
        setErrorInfo("网络竟然崩溃了","主人别急，点击重新加载试试~~",R.drawable.nonet);
        refreshTv.setText("重新加载");
        return true;
    }

    public void setErrorInfo(String title,String desc,int imageId){
        errorTitleTv.setText(title);
        errorDescTv.setText(desc);
        error_Iv.setImageResource(imageId);
    }


    @Override
    public void showMainView() {
        mainView.setVisibility(View.VISIBLE);
        nodataView.setVisibility(View.INVISIBLE);
    }

    public void toRefresh() {
        getDataFromServer();
    }

    public void onRightClick(View view) {

    }


    @Override
    public void loadFail() {
        twinkCompleted();
    }


    @Override
    public void toLogin() {
        Intent intent = new Intent();
        intent.setAction(getPackageName() + ".activity.neet.to.login");
        startActivityForResult(intent, 0x0000);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == 0x0000) {
            getDataFromServer();
        }
    }

    //网络传输文本判空规则
    public static boolean isNull(String s) {
        if (s == null || s.trim().isEmpty() || "null".equals(s) || "(null)".equals(s)) {
            return true;
        }
        return false;
    }

    public boolean isOutTime() {
//        String date = "2021-05-20 00:00:00";
//        long outTime = Kits.Date.getYmdhmsTime(date);
//        NLog.d(TAG,"outTime="+outTime);
//        long currentTime = Calendar.getInstance().getTimeInMillis();
//        if(outTime < currentTime){
//            return true;
//        }else{
//            return false;
//        }
        return false;
    }

}
